import {Component} from "react";
import {Table, Button} from "antd";
import {connect} from "dva";
import {Link} from 'dva/router';
import {PAGE_SIZE} from "../constants";

@connect(state => ({
  dataList: state.menu.dataList,
  page: state.menu.page,
  total: state.menu.total,
  pageSize: state.menu.pageSize
}))
export default class Menus extends Component {
  constructor(props) {
    super(props);
    this.initTable();
  }

  componentWillMount() {
    const {dispatch} = this.props;
    dispatch({
      type: "menu/fetch",
      payload: {
        page: 1,
        pageSize: PAGE_SIZE
      }
    });
  }

  initTable() {
    this.columns = [{
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    }, {
      title: "名称",
      dataIndex: "name",
      key: "name"
    }, {
      title: "地址",
      dataIndex: "url",
      key: "url"
    }, {
      title: "操作",
      render(text, record) {
        return (
          <span>
            <Link to={{
              pathname: 'menu/edit',
              search: `id=${record.id}`,
            }}>
              <Button size="small" type="primary">编辑</Button>
            </Link>
          </span>
        );
      }
    }];
  }

  render() {
    const {dataList, pageSize, page, total, dispatch} = this.props;
    const tableConfig = {
      dataSource: dataList,
      columns: this.columns,
      pagination: {
        defaultCurrent: page,
        defaultPageSize: pageSize,
        showSizeChanger: true,
        showQuickJumper: true,
        total,
        pageSize,
        current: page,
        onShowSizeChange: (current, pageSize) => {
          dispatch({
            type: 'menu/fetch',
            payload: {
              page: current,
              pageSize: pageSize
            }
          });
        },
        onChange: (current, pageSize) => {
          dispatch({
            type: 'menu/fetch',
            payload: {
              page: current,
              pageSize: pageSize
            }
          });
        },
      }
    };
    return (
      <Table {...tableConfig}/>
    );
  }
}
